package eva.savant.setup

import groovy.sql.Sql

class Persistence {

  String module

  String pathSqlFile

  String pathSource

  String pathPackage

  def nameTrs= []//['VENTA_DETALLE','PEDIDO_DETALLE','COMPRA_DETALLE','SOLICITUDCOMPRA_DETALLE']


  public Persistence(String module, String pathSqlFile, String pathSource, String pathPackage) {

      this(pathSqlFile,pathSource,pathPackage)

      this.module= module
  }

  public Persistence(String pathSqlFile, String pathSource, String pathPackage) {

    this.pathSqlFile= pathSqlFile

    this.pathSource = pathSource

    this.pathPackage= pathPackage
  }

  public def generatePersistence() {

    def reader= new BufferedReader(new FileReader(pathSqlFile))

    def lsTable= new LinkedHashMap<String,ArrayList<String>>()

    String line

    //noinspection GroovyUnusedAssignment
    while( (line=reader.readLine()) != null ) {

    if(line.startsWith('create table')) addTable(lsTable,line,reader) 
            
    if(line.startsWith('alter table ')) addForeignKeys(lsTable,line,reader.readLine()) }

      
    buildFileClass(lsTable)
  }

  def buildFileClass(Map<String,ArrayList<String>> lsTable) {

    def files= createFileField(lsTable); createFileLsField(files,lsTable)


    for (id in files.keySet()) {

    def fileClass= files.get(id)

    createFileConstructorField(fileClass,toClassName(id))

    createFileGetSetField(fileClass)

    createFilePrimaryKeyField(fileClass)

    def close= fileClass.get('close'); close= close==null? '\n}' : '\n}\n'+ close; fileClass.put('close',close) }


    createFieldCascadeType(files)

    createFileLazyCollection(files)

    createFile(files)
  }

  def createFileField(Map<String,ArrayList<String>> lsTable){

    def files= new LinkedHashMap<String,Map<String,String>>()


    for (id in lsTable.keySet()) { //id= name table

      def info= lsTable.get(id)

      def res= new ArrayList<String>()

      def ind= -1


      for(data in info) {

      data= filterInfo(data)

      if(!data.startsWith(':')) ind ++

      else data= data.substring(1,data.length())

      res.add(data) }


      res.set(0,id+':'+ind)

      lsTable.put(id, res)

      files.put(id,createFileClass(res))
    }


    def stock=     '\n'

    stock= stock + '\n    @Transient'

    stock= stock + '\n    private BigDecimal stock; // Stock Actual'

    for(id in nameTrs) { def file= files.get(id); file.put('STOCK_TS',stock) }


    return files
  }

  def createFileLsField(Map<String,Map<String,String>> files, Map<String,ArrayList<String>> lsTable) {

    for (id in lsTable.keySet()) {

    def info= lsTable.get(id)

    def tableName= info.get(0).split(':')[0]

    def ini= Integer.parseInt(info.get(0).split(':')[1])


      for(int i=ini+1; i<info.size(); i++) {

      def aux= info.get(i).split(':')

      def fileClass= files.get(aux[1])

      def className= toClassName(tableName).substring(2) //Exclude module
                 //println 'aux: '+aux[0]
      //def filed= classNameToField(aux[1]).substring(2).toLowerCase() //Exclude module

      def field= aux[0].replace('ID_','').toLowerCase() //Exclude module


      def      resultF = '\n' + '    @OneToMany'

      resultF= resultF + '\n' + '    (mappedBy = \"'+field+'\")'

      resultF= resultF + '\n' + '    private Collection<'+className+'> ls'+className+';'

      //println 'SET: '+toClassName(tableName) + ' tableName '+aux[1]
      setPathPackage(fileClass,toClassName(tableName)) //Include module

      fileClass.put('ls'+className,resultF) }
    }
  }

  def createFileGetSetField(Map<String,String> fileClass) {

    def extendEntity= isExtendEntity(fileClass)

    def getSet= ''


    for (id in fileClass.keySet()) {

    if(!id.equalsIgnoreCase('import')      && !id.equalsIgnoreCase('class')    && !id.equalsIgnoreCase('package') &&

       !id.equalsIgnoreCase('constructor') && !id.equalsIgnoreCase('FECHA_ID') && !id.equalsIgnoreCase('close') && !id.endsWith('_PK'))

    if(!extendEntity )

    getSet= getSet + buildGetSet(fileClass[id].split('\n')[3].trim())

    else if(!id.equalsIgnoreCase('OPERACION_ID') && !id.equalsIgnoreCase('SOCIEDAD_ID') && !id.equalsIgnoreCase('USUARIO_ID'))

    getSet= getSet + buildGetSet(fileClass[id].split('\n')[3].trim())  }


    if(!extendEntity) {

    def         updateTime = '\n' + ''
    updateTime= updateTime + '\n' + '    @PreUpdate'
    updateTime= updateTime + '\n' + '    @PrePersist'
    updateTime= updateTime + '\n' + '    public void updateTimeFechaId() {'
    updateTime= updateTime + '\n' + ''
    updateTime= updateTime + '\n' + '        this.fechaId = new Timestamp(new java.util.Date().getTime());'
    updateTime= updateTime + '\n' + '    }'

    getSet= getSet + updateTime }


    createFileImportField(fileClass,getSet)

    fileClass.put('getset',getSet)
  }

  def createFileConstructorField(Map<String,String> fileClass, String nameClass) {

    def fields= ''

    for (id in fileClass.keySet()) {

    if(!id.equalsIgnoreCase('import') && !id.equalsIgnoreCase('class')  && !id.equalsIgnoreCase('package') && !id.equalsIgnoreCase('constructor') &&

       !id.equalsIgnoreCase('FECHA_ID') && !id.equalsIgnoreCase('close') && !id.startsWith('ls') && !id.endsWith('_PK') && !id.endsWith('_TS'))

    fields= fields + getParameterConstructor(fileClass.get(id))  }


    fileClass.put('constructor','\n\n'+buildConstructor(nameClass,fields))
  }

  def createFilePrimaryKeyField(Map<String,String> fileClass) {

    def fieldsPK= ''

    for (id in fileClass.keySet())

    if(id.endsWith('_PK')) fieldsPK= fieldsPK + id + ','


    if(fieldsPK.length() > 5) {

    fieldsPK= fieldsPK.replace('ID_','').replace('_PK','')

    fieldsPK= fieldsPK.substring(0,fieldsPK.length()-1)

    def fieldsPKs= fieldsPK.split(',')

      for(fld in fieldsPKs) {

      def res= classNameToField(fld)

      def find= 'this.'+res+'= '+res+';'

      def rmp= find + '\n\n        this.'+res+'_Id= '+res+' != null? '+res+'.getId() : null;'

      def val= fileClass.get('constructor'); val= val.replace(find,rmp); fileClass.put('constructor',val)


      find= 'this.'+res+' = '+res+';'

      rmp= find + '\n\n        this.'+res+'_Id= '+res+' != null? '+res+'.getId() : null;'

      val= fileClass.get('getset'); val= val.replace(find,rmp); fileClass.put('getset',val) }
    }
  }

  def setPathPackage(Map<String,String> fileClass, String impClassName) { //Include module

    def pPackage= pathPackage + '.' + impClassName.toLowerCase().substring(0,2)

    def imp= fileClass.get('import'), pak= fileClass.get('package')

    if( !pak.contains(pPackage) ) {    //!imp.contains(pPackage) &&

    imp= '\nimport ' + pPackage + '.' + impClassName.substring(2) + ';' + imp; fileClass.put('import',imp) }
  }

  def createFileImportField(Map<String,String> fileClass, String getSet){

    if(isExtendEntity(fileClass)) {

    def c= fileClass.get('class'); c= c.replace('{','extends '+this.pathPackage+'.Entity {'); fileClass.put('class',c)

    fileClass.remove('FECHA_ID'); fileClass.remove('OPERACION_ID'); fileClass.remove('SOCIEDAD_ID'); fileClass.remove('USUARIO_ID'); }


    if(getSet.indexOf('Timestamp') < 0) {

    def imp= fileClass.get('import'); imp= imp.replace('\nimport java.sql.Timestamp;',''); fileClass.put('import',imp) }


    if(getSet.indexOf('Collection<') > -1) {

    def imp= fileClass.get('import'); imp= imp + '\nimport java.util.Collection;'; fileClass.put('import',imp) }
  }

  def createFieldCascadeType(Map<String,Map<String,String>> files) {

    def detalle= ['VENTA'          :'lsVentaDetalle',
                  'COMPRA'         :'lsCompraDetalle',
                  'CM_SOLICITUD'   :'lsSolicitudDetalle',
                  'ENTREGA'        :'lsEntregaDetalle',
                  'CG_CUENTA'      :'lsCuenta',
                  'CG_ASIENTO'     :'lsPartida',
                  'CG_PREASIENTO'  :'lsPreasientoDetalle',
                  'CG_DOCUMENTO'   :'lsDocumentoDetalle',
                  'VT_CANAL'       :'lsPrecio',
                  'MT_MOVIMIENTO'  :'lsKardex',
                  'MT_ALMACENERO'  :'lsAlmaceneroAlmacen',
                  'MT_ALMACEN'     :'lsAlmacenDetalle',
                  'DV_DESPACHADOR' :'lsDespachadorOficina',
                  'DV_AUTORIZADOR' :'lsAutorizadorOficina',
                  'DV_SUPERVISOR'  :'lsSupervisorOficina',
                  'DV_DEVOLUCION'  :'lsDevolucionDetalle',
                  'VT_VENTA'       :'lsVentaDetalle',
                  'VT_PEDIDO'      :'lsPedidoDetalle',
                  'VT_GVENDEDOR'   :'lsGvendedorVendedor'/*,
                  'VT_CLIENTE'     :'lsInterlocutor'*/]

    for (id in files.keySet()) {

    def fileClass= files.get(id)

    def name= detalle.get(id)

    if(name != null)  {

    def fld= fileClass.get(name).replace(')',', cascade = CascadeType.ALL, orphanRemoval = true) @LazyCollection(LazyCollectionOption.FALSE)')

    fileClass.put(name,fld)

    def pkg= fileClass.get('import');

        pkg= pkg + '\nimport org.hibernate.annotations.LazyCollection;';

        pkg= pkg + '\nimport org.hibernate.annotations.LazyCollectionOption;';

        fileClass.put('import',pkg) } }
  }

  def createFileLazyCollection(Map<String,Map<String,String>> files) {

    def list= ['AD_MENU':'lsMenu']

    for (id in list.keySet()) {

    def fileClass= files.get(id); if(fileClass == null) continue

    def value= fileClass.get(list[id]); if(value == null) continue


    fileClass.put(list[id],value.replace(')',') @LazyCollection(LazyCollectionOption.FALSE)'))


    def pkg= fileClass.get('import');

        pkg= pkg + '\nimport org.hibernate.annotations.LazyCollection;';

        pkg= pkg + '\nimport org.hibernate.annotations.LazyCollectionOption;';

        fileClass.put('import',pkg) }
  }

  def createFile(Map<String,Map<String,String>> files) {

    for (key in files.keySet()) { def fileClass= files.get(key)


    def info= ''

    for (id in fileClass.keySet()) if(!id.equals('close')) info= info + fileClass.get(id) + '\n'

    info= info + fileClass.get('close')


    if(module != null && !fileClass.get('package').endsWith(module+';')) continue  //only module


    createFileJava(fileClass.get('package'),toClassName(key)+'.java',info)

    System.out.println(info + '\n\n')
    }

  }

  def isExtendEntity(Map<String,String> fileClass){

    return fileClass.get('OPERACION_ID')!= null &&

           fileClass.get('SOCIEDAD_ID') != null &&

           fileClass.get('USUARIO_ID')  != null
  }

  def filterInfo(String info){

    info= info.replace('primary key (','PRIMARYKEY:')

    info= info.replace('not null',':false')

    info= info.replace('default NULL','')

    info= info.replace('text',':String(500)')

    info= info.replace('varchar',':String')

    info= info.replace('char',':String')

    info= info.replace('integer ',':Integer(10)')

    info= info.replace('tinyint ',':Integer(10)')

    info= info.replace('date ',':Date(10)')

    info= info.replace('datetime ',':Timestamp(19)')

    info= info.replace('time ',':Time(8)')

    info= info.replace('double',':BigDecimal(14,4)')

    info= info.replace('decimal',':BigDecimal')

    info= info.replace(' auto_increment',':auto_increment')

    info= info.replace('default 1','')

    info= info.replace('default 0.0000','')

    info= info.replace('default 0.00','')

    info= info.replace('default 0','')

    info= info.replace("default '2000-01-01'",'')

    int ind= info.indexOf("comment '")

    int aux= info.indexOf(':false')

    if(ind > 0) { info= info.substring(0,info.length()-2)

    info= aux==-1? info.replace("comment '",':true:') : info.replace("comment '",':')
    }

    def tmp= info.split(':')

    def res= ''

    for(s in tmp) res= res + s.trim() + ':'

    return res.substring(0,res.length()-1)
  }

  def filterLineSQL(String sql) {

    sql= sql.trim()

    if(sql.startsWith('create table')) return sql.substring(13)

    if(sql.startsWith('primary key')) return sql.substring(0,sql.length()-1)

    if(sql.startsWith('(')) return null

    if(sql.startsWith(')')) return null

    if(sql.endsWith(',')) return sql.substring(0,sql.length()-1)

    return sql
  }

  def addTable(Map<String,ArrayList<String>> lsTable, String line, BufferedReader reader) {

    def table= new ArrayList<String>(); table.add(filterLineSQL(line))


    while( (line=reader.readLine()) != null && !line.startsWith(')') ) {

    def lineSql= filterLineSQL(line); if(lineSql != null) table.add(lineSql+'\n')  }


    lsTable.put(table.get(0),table)
  }

  def addForeignKeys(Map<String,ArrayList<String>> lsTable, String info1, String info2) {

    def ind= info1.indexOf(' add constraint ')

    def name= info1.substring( 12, ind )

    def list= lsTable.get(name)

    def aux= filterForeignKeys(info1,info2)

    if(list != null) list.add(aux)
  }

  def filterForeignKeys(String info1, String info2) {

    def info= info1.trim()+':'+info2.trim()

    def ind1= info.indexOf('foreign key (')

    def ind2= info.indexOf(') on delete ')

    info= ':'+info.substring(ind1+13,ind2)

    info= info.replace('):references ',':')

    info= info.replace(' (',':')

    return info
  }

  def addHeadCreateFileClass(tableName, String className, LinkedHashMap<String,String> fileClass) {

    def module= className.substring(0,2).toLowerCase(); className= className.substring(2) //Create module

    def      resultP =        'package ' + pathPackage + '.' + module + ';' //Include module

    def      resultI = '\n' + 'import javax.persistence.*;'

    def      resultC = '\n' + '@Table(name=\"'+tableName+'\")'
    resultC= resultC + '\n' + '@javax.persistence.Entity(name = \"'+module+'.'+className+'\")'
    resultC= resultC + '\n' + 'public class '+className+' {'

    fileClass.put('package',resultP)

    fileClass.put('import',resultI)

    fileClass.put('class',resultC)
  }

  def addFiledCreateFileClass(LinkedHashMap<String,String> fileClass, List<String> info) {

    def end= Integer.parseInt(info.get(0).split(':')[1])

    def isDate= false, isTime= false, isTimestamp= false, isDecimal= false

      println 'Table: ' + info[0]

      for(def i=1; i<=end-1; i++) {

        def data= info[i].split(':')

        def name=     data[0]
        def length=   getLength(data[1])
        def nullable= data[2]
        def type=     getType(data[1])
        def filed=    toFiledName(name)
        def comment=  getComment(data)

        def      resultF = '\n' + '    ' + (i==1? '@Id'+getAutoIncrement(data) : '@Basic')
        resultF= resultF + '\n' + '    @Column(name = \"'+name+'\", length = '+length+', nullable = '+nullable+')'
        resultF= resultF + '\n' + '    private '+type+' '+(i==1? 'id' : filed)+'; '+comment


        if(type.equalsIgnoreCase('Timestamp')) {

        resultF= resultF.replace('@Basic','@Basic @Temporal(TemporalType.TIMESTAMP)')

        resultF= resultF.replace('Timestamp','Date')

        type= 'Date'}


        fileClass.put(name,resultF)

        if(type.equalsIgnoreCase('Date')       && !isDate)      isDate=true
        if(type.equalsIgnoreCase('Time')       && !isTime)      isTime=true
        if(type.equalsIgnoreCase('Timestamp')  && !isTimestamp) isTimestamp=true
        if(type.equalsIgnoreCase('BigDecimal') && !isDecimal)   isDecimal=true
      }

      for(int i=end+1; i<info.size(); i++) {

        def aux=    info[i]
        def tmp=    aux.split(':')
        def type=   toClassName(tmp[1]).substring(2) //Exclude module
        //def filed=  classNameToField(tmp[1]).substring(2).toLowerCase() //Exclude module

        def filed=  tmp[0].replace('ID_','').toLowerCase()

        def name=   tmp[0]
        def comment=''
        def nullable= 'false'

        def s= fileClass.get(name)


        if(s != null) {

        int ind= s.indexOf('//'); if(ind > 0) comment= s.substring(ind)

            ind= s.indexOf('true)'); if(ind > 0) nullable= 'true' }


        def      resultF = '\n' + '    @ManyToOne'
        resultF= resultF + '\n' + '    @JoinColumn(name = \"'+name+'\", nullable = '+nullable+')'
        resultF= resultF + "\n" + '    private '+type+' '+filed+'; '+comment


        setPathPackage(fileClass,toClassName(tmp[1])) //Include module

        fileClass.put(name,resultF)
      }


    if(isDecimal)   fileClass.put('import',fileClass.get('import') + '\n' + 'import java.math.BigDecimal;')

    if(isDate)      fileClass.put('import',fileClass.get('import') + '\n' + 'import java.util.Date;')

    if(isTime)      fileClass.put('import',fileClass.get('import') + '\n' + 'import java.sql.Time;')

    if(isTimestamp) fileClass.put('import',fileClass.get('import') + '\n' + 'import java.sql.Timestamp;')


    buildClassPK(fileClass,info,end)
  }

  def getTypeFromField(List<String> info, int end, String field) {

    for(def i=1; i<=end-1; i++) {

      def data= info.get(i).split(':')

      def name= data[0]

      def type= getType(data[1])

      if(name.equals(field)) return type
    }

    return ''
  }

  def buildClassPK(LinkedHashMap<String,String> fileClass, List<String> info, int end) {

    def primaryKey= info.get(end).replace('PRIMARYKEY:','').split(', ') //IMPORT Create Dual Key Foreign

    if(primaryKey.length < 2) return


    def primaryKeyType= new String[primaryKey.length]

    for(int i=0; i < primaryKey.length; i++)

    primaryKeyType[i]=  getTypeFromField(info,end,primaryKey[i])


    def fields= ''

    for(int i=0; i < primaryKey.length; i++) {

      def type=  toClassName(primaryKey[i].replace('ID_',''))

      def filed= classNameToField(primaryKey[i].replace('ID_',''))


      fields= fields + primaryKeyType[i] + ' ' + filed + '_Id, '


      def foreign= fileClass.get(primaryKey[i])

      fileClass.put(primaryKey[i],foreign.replace('nullable = false','insertable = false, updatable = false'))


      def primary= '\n    @Id\n    @Column(name=\"'+primaryKey[i]+'\")\n    private '+primaryKeyType[i]+' '+filed+'_Id; //ID '+type

      fileClass.put(primaryKey[i]+'_PK',primary.replace('null',''))
    }

    def name= toClassName(info.get(0).split(':')[0]) + 'PK'

    def className= name.substring(2) //Exclude module

    fileClass.put('import',fileClass.get('import') + '\n' + 'import java.io.Serializable;')

    fileClass.put('class',fileClass.get('class').replace('@javax.persistence.Entity',

                                                         '@IdClass('+className+'.class)\n@javax.persistence.Entity'))

    def pk=      '\nclass '+className+' implements Serializable {'
        pk= pk + '\n'

        for(int i=0; i<primaryKey.length; i++) {

        def filed=  classNameToField(primaryKey[i].replace('ID_',''))

        pk= pk + '\n'
        pk= pk + '\n' + '    private '+primaryKeyType[i]+' '+filed+'_Id;' }

        pk= pk + '\n'
        pk= pk + '\n'
        pk= pk + '\n' + buildConstructor(name,fields)
        pk= pk + '\n'

        for(int i=0; i<primaryKey.length; i++) {

        def filed=  classNameToField(primaryKey[i].replace('ID_',''))

        pk= pk + buildGetSet('public '+primaryKeyType[i]+' '+filed+'_Id') }

        pk= pk + '\n'
        pk= pk + '\n    @Override'
        pk= pk + '\n    public boolean equals(Object object) {'
        pk= pk + '\n'
        pk= pk + '\n        if(object == null) return false;'
        pk= pk + '\n'
        pk= pk + '\n        if(object == this) return true;'
        pk= pk + '\n'
        pk= pk + '\n        if( !(object instanceof '+className+') ) return false;'
        pk= pk + '\n'
        pk= pk + '\n'
        pk= pk + '\n        '+className+' pk = ('+className+') object;'
        pk= pk + '\n'
        pk= pk + '\n'


        for(int i=0; i<primaryKey.length; i++) {

        def filed= classNameToField(primaryKey[i].replace('ID_',''))

        if(i==0) pk= pk + '\n        return ' else pk= pk +'\n               '

        pk= pk + 'pk.get'+toClassName(filed)+'_Id().equals('+filed+'_Id) &&'
        pk= pk + '\n' }

        pk= pk.substring(0,pk.length()-4) +';'

        pk= pk + '\n    }'
        pk= pk + '\n'
        pk= pk + '\n    @Override'
        pk= pk + '\n    public int hashCode() {'
        pk= pk + '\n'
        pk= pk + '\n        int hashCode = 17;'
        pk= pk + '\n'

        for(int i=0; i<primaryKey.length; i++) {

        def filed= classNameToField(primaryKey[i].replace('ID_',''))

        pk= pk + '\n        hashCode = 31 * hashCode + '+filed+'_Id.hashCode();'
        pk= pk + '\n' }

        pk= pk + '\n        return hashCode;'
        pk= pk + '\n    }'
        pk= pk + '\n'
      pk= pk + '\n}'


    fileClass.put('close',pk)
  }

  def createFileClass(List<String> info) {

    def fileClass= new LinkedHashMap<String,String>()

    def tableName= info.get(0).split(':')[0]

    def className= toClassName(tableName)

    addHeadCreateFileClass(tableName, className, fileClass)

    addFiledCreateFileClass(fileClass, info)

    return fileClass
  }

  def buildConstructor(String nameClass, String fields){

    nameClass= nameClass.substring(2) //Exclude module

    fields= fields.substring(0,fields.length()-2)

    def cad= fields.trim().split(',')

    def aux= '    public ' + nameClass + '(' + fields + ') {\n\n'


    for(tmp in cad) {

    def field= tmp.trim().split(' ')[1]

    aux= aux + '        this.' + field + '= ' + field + ';\n\n' }


    return aux + '    }\n\n' + '    public '+nameClass+'() {\n\n    }'
  }

  def getParameterConstructor(String info){

    def cad= info.split(';')[0]

    def aux= cad.split(' ')

    def type=aux[aux.length-2].trim()

    def nom= aux[aux.length-1].trim()

    return type + ' ' + nom + ', '
  }

  def buildGetSet(String info){

    def cad= info.split(';')[0]

    def aux= cad.split(' ')

    def type=aux[1]

    def nom= aux[2]

    def tmp= nom.substring(0,1).toUpperCase() + nom.substring(1)

    def getSet= '\n'
        getSet= getSet + '\n' + '    public '+type+' get'+tmp+'() {'
        getSet= getSet + '\n' + '    '
        getSet= getSet + '\n' + '        return '+nom+';'
        getSet= getSet + '\n' + '    }'
        getSet= getSet + '\n' + '    '
        getSet= getSet + '\n' + '    public void set'+tmp+'('+type+' '+nom+') {'
        getSet= getSet + '\n' + '    '
        getSet= getSet + '\n' + '        this.'+nom+' = '+nom+';'
        getSet= getSet + '\n' + '    }'

    return getSet
  }

  def getAutoIncrement(String[] data) {

    for(s in data)

    if(s.equals('auto_increment'))

    return ' @GeneratedValue(strategy = GenerationType.IDENTITY)'

    return '';
  }

  def getComment(String[] data) {

    return data.length > 3? '//'+data[data.length-1] : ''
  }

  def getLength(String data) {

    def ind= data.indexOf('(')

    def aux= data.substring(ind+1,data.length()-1)

    def tmp= aux.split(',')

    def res= tmp[0]

    if(tmp.length > 1) res= res + ', precision = ' + tmp[1]

    return res
  }

  def getType(String data) {

    return data.substring(0,data.indexOf('('))
  }

  def toClassName(String tableName) {

    return toName(tableName,true)
  }

  def toFiledName(String campName) {

    return toName(campName,false)
  }

  def toName(String name, boolean band) {

    def res= ''

    char[] car= name.toLowerCase().toCharArray()


    for(int i=0; i<car.length; i++) {

    if(i==0 && band)                car[i]= Character.toUpperCase(car[i])

    else if(i > 0 && car[i-1]=='_') car[i]= Character.toUpperCase(car[i])

    if(car[i]!='_') res= res + car[i] }


    return res
  }

  def classNameToField(String tableName) {

    def name= toClassName(tableName)

    return name.substring(0,1).toLowerCase() + name.substring(1)
  }

  def createFileJava(String pathPackage, String nameFile, String contentFile) {

    pathPackage= pathPackage.replace('package ','')

    pathPackage= pathPackage.replace(';','')

    nameFile= nameFile.substring(2)

    nameFile= pathSource + pathPackage.replace(".","/") + '/' + nameFile

    def file = new File( nameFile )

    if(file.exists()) file.delete()

    def writer= new FileWriter(file,true)

    def pw = new PrintWriter(writer)

    pw.println(contentFile)

    pw.flush()

    pw.close()
  }

}

class PersistenceData {

def soc= 'CB'

def file="INSERT INTO GL_SOCIEDAD VALUES  ('${soc}', 'SIN NOMBRE', 'SIN DIRECCION', '123456', '0', '1', '2013-01-01 00:00:01');" +

         "INSERT INTO GL_PARAMETRO VALUES ('${soc}01','01','mail.transport.protocol','smtp',         '0','1','${soc}','1','2013-01-01 00:00:01');" +
         "INSERT INTO GL_PARAMETRO VALUES ('${soc}02','02','mail.store.protocol',    'imap',         '0','1','${soc}','1','2013-01-01 00:00:01');" +
         "INSERT INTO GL_PARAMETRO VALUES ('${soc}03','03','mail.smtp.host',         '127.0.0.1',    '0','1','${soc}','1','2013-01-01 00:00:01');" +
         "INSERT INTO GL_PARAMETRO VALUES ('${soc}04','04','mail.store.host',        '127.0.0.1',    '0','1','${soc}','1','2013-01-01 00:00:01');" +
         "INSERT INTO GL_PARAMETRO VALUES ('${soc}05','05','mail.store.username',    'administrador','0','1','${soc}','1','2013-01-01 00:00:01');" +
         "INSERT INTO GL_PARAMETRO VALUES ('${soc}06','06','mail.store.password',    'administrador','0','1','${soc}','1','2013-01-01 00:00:01');" +

         "INSERT INTO GL_PERSONA  VALUES  ('1', null, 'Super Usuario', 'SIN DIRECCION', '12345678', '1', '${soc}', '1', '2013-01-01 00:00:01');" +
         // cambiar id persona usuario rol_usuario
         "INSERT INTO AD_USUARIO  VALUES  ('1', '1', 'admin', 'admin', '2013-01-01', null, null, null, null, null, '2013-01-01', '1', '0', '1', '${soc}', '1', '2013-01-01 00:00:01');" +

         "INSERT INTO AD_SISTEMA VALUES   ('${soc}10', '10', 'Savant', '', 'localhost:8080/savant', '', '1', '${soc}', '1', '2013-01-01 00:00:01');" +

         "INSERT INTO AD_TRANSACCION VALUES ('${soc}10', '${soc}10', '10','Rol Administrador',  '/business/splash.xhtml',                     '0','1','${soc}','1','2013-01-01 00:00:01');" +
         "INSERT INTO AD_TRANSACCION VALUES ('${soc}101','${soc}10','101','Gestion Sistema',    '/business/administrador/IMSistema.xhtml',    '1','1','${soc}','1','2013-01-01 00:00:01');" +
         "INSERT INTO AD_TRANSACCION VALUES ('${soc}102','${soc}10','102','Gestion Transaccion','/business/administrador/IMTransaccion.xhtml','1','1','${soc}','1','2013-01-01 00:00:01');" +
         "INSERT INTO AD_TRANSACCION VALUES ('${soc}103','${soc}10','103','Gestion Rol',        '/business/administrador/IMRol.xhtml',        '1','1','${soc}','1','2013-01-01 00:00:01');" +
         "INSERT INTO AD_TRANSACCION VALUES ('${soc}104','${soc}10','104','Gestion Persona',    '/business/global/IMPersona.xhtml',           '1','1','${soc}','1','2013-01-01 00:00:01');" +
         "INSERT INTO AD_TRANSACCION VALUES ('${soc}105','${soc}10','105','Gestion Usuario',    '/business/administrador/IMUsuario.xhtml',    '1','1','${soc}','1','2013-01-01 00:00:01');" +
         "INSERT INTO AD_TRANSACCION VALUES ('${soc}106','${soc}10','106','Cambiar Password',   '/business/administrador/IMPassword.xhtml',   '1','1','${soc}','1','2013-01-01 00:00:01');" +

         "INSERT INTO AD_MENU VALUES ('${soc}10',           null,  '${soc}10','Rol Administrador',  '1', '1','${soc}','1','2013-01-01 00:00:01');" +
         "INSERT INTO AD_MENU VALUES ('${soc}1000',   '${soc}10',        null,'Datos Maestros',     '10','1','${soc}','1','2013-01-01 00:00:01');" +
         "INSERT INTO AD_MENU VALUES ('${soc}100001','${soc}1000','${soc}101','Gestion Sistema',    '10','1','${soc}','1','2013-01-01 00:00:01');" +
         "INSERT INTO AD_MENU VALUES ('${soc}100002','${soc}1000','${soc}102','Gestion Transaccion','10','1','${soc}','1','2013-01-01 00:00:01');" +
         "INSERT INTO AD_MENU VALUES ('${soc}100003','${soc}1000','${soc}103','Gestion Rol',        '10','1','${soc}','1','2013-01-01 00:00:01');" +
         "INSERT INTO AD_MENU VALUES ('${soc}100004','${soc}1000','${soc}104','Gestion Persona',    '10','1','${soc}','1','2013-01-01 00:00:01');" +
         "INSERT INTO AD_MENU VALUES ('${soc}100005','${soc}1000','${soc}105','Gestion Usuario',    '10','1','${soc}','1','2013-01-01 00:00:01');" +
         "INSERT INTO AD_MENU VALUES ('${soc}100006','${soc}1000','${soc}106','Cambiar Password',   '10','1','${soc}','1','2013-01-01 00:00:01');" +

         "INSERT INTO AD_ROL VALUES ('${soc}10', '${soc}10', '${soc}10', '10', 'Rol Administrador', '1', '${soc}', '1', '2013-01-01 00:00:01');" +

         "INSERT INTO AD_USUARIO_ROL VALUES ('1', '${soc}10', null, null, '1', '${soc}', '1', '2013-01-01 00:00:01');"

         public void insert() {

         def sql= Sql.newInstance('jdbc:mysql://localhost:3306/savant','soporte','administrador','com.mysql.jdbc.Driver')

         def array= file.split(';'); for(data in array) sql.executeInsert(data) }
}

//def persistence= new Persistence('X:/Workspace/savant.sql','X:/Workspace/Savanti/Core/src/','eva.savant.businessobject')

def persistence= new Persistence('vt','X:/Workspace/savanti.sql','X:/Workspace/Savanti/Core/src/','eva.savant.businessobject')

persistence.generatePersistence()

//new PersistenceData().insert()